#coding:utf-8

import smtplib
import xlrd
from email.mime.text import MIMEText
import sys 
import os
import re
import traceback

name_dic = {}
email_dic = {}
custom_dic = {}
follow_flag_dic = {}
bank_dic = {}
           
class SendMail(object):
    def __init__(self):
        self.maildt = os.getcwd() + '\\' + 'mail' + '\\Westpac'
        
        
    def send_mail(self, mailto, sub, content):
        mail_user="xxx@tigerloans.com.au"                       #用户名
        mail_pass="xxx"                      #密码
        mail_postfix="tigerloans.com.au"                #邮箱的后缀
        mail_host="mail.tigerloans.com.au" 
        me="Case Status"+"<"+mail_user+">"
        msg = MIMEText(content, 'html', 'utf-8')  
        msg['Subject'] = sub
        msg['From'] = me
        msg['To'] = mailto                #将收件人列表以‘；’分隔
        mail_list = mailto.split(';')
        try:
            server = smtplib.SMTP()
            server.connect(mail_host)                            #连接服务器
            server.login(mail_user,mail_pass)               #登录操作
            server.sendmail(me, mail_list, msg.as_string())
            server.close()
            return True
        except Exception, e:
            print str(e)
            return False


    def getfiles(self):
        file_list = []
        for root, path, filename in os.walk(self.maildt):
            for i in filename:
                if(i.endswith('.html')):
                    file_list.append(root + '\\' + i)
        return file_list 
                
    def readxls(self):
        direcotry = os.getcwd() + '\\' + 'Follow Up.xlsx'
        data = xlrd.open_workbook(direcotry)
        table1 = data.sheets()[0]
        table2 = data.sheets()[1]
        table1_rs = table1.nrows
        table2_rs = table2.nrows
        
        for i in range(table1_rs):
            nbr = str(table1.cell(i, 5).value)
            nbr = nbr.replace('-', '').replace(' ', '')
            cter = str(table1.cell(i, 1).value)
            cter = cter.replace(' ', '').lower()
            cster = str(table1.cell(i, 3).value)
            bank = str(table1.cell(i, 6).value)
            flag = str(table1.cell(i, 11).value)
            flag = flag.lower()
            name_dic[nbr] = cter
            custom_dic[nbr] = cster
            follow_flag_dic[nbr] = flag
            bank_dic[nbr] = bank
            
        for i in range(table2_rs):
            cnter = str(table2.cell(i, 0).value)
            cnter = cnter.replace(' ', '').lower()
            email_dic[cnter] = table2.cell(i, 1).value

    def clearcontent(self, content):
        patterns = (
                    (r'<HEAD>.*?</HEAD>', r'', re.S),
                    (r'<MAP.*?</MAP>', r'', re.S),
                    (r'<IMG.*?/>', r'', re.S),
                    (r'&nbsp;', r'', re.S),
                    (r'&nbsp', r'', re.S),
                    (r'<input.*?>', r'', re.S), 
                    (r'<TD colspan="3">.*?</TD>', r'', re.S),
                    (r'Copyright.*?/FONT>', r'', re.S),
                    
                )
        for a, b, c in patterns:
            content = re.sub(a, b, content, flags=c)
        return content

    def Sdmail(self, dname):
        filename = os.path.split(dname)[1]
        nbr = filename.split('.')[0]
        print 'Nbr is : %s' % nbr
        
        if follow_flag_dic.has_key(nbr):
            YoN = follow_flag_dic[nbr]
            if 'n' in YoN:
                print '%s no need to follow up.' % nbr
                return True

        if name_dic.has_key(nbr):
            consultant = name_dic[nbr]
            bank_name = bank_dic[nbr]
            
            if email_dic.has_key(consultant):
                e_mail = email_dic[consultant]
                with open(dname, 'r') as f:
                    content = f.read()
                content = self.clearcontent(content)
               
                if custom_dic.has_key(nbr):
                    custname = custom_dic[nbr]
                else:
                    custname = ''
                subject = '%s %s %s %s' % (nbr, custname, bank_name, consultant)
                self.send_mail(e_mail, subject, content)
                print "%s consultant: %s , e_mail: %s, already send done." %(nbr, consultant, e_mail)
                flag = True
            else:
                print '%s not found in consultant table.' % name_dic[nbr]
                flag = False
        else:
            
            print '%s not found in follow table' % nbr
            flag = False
        return flag
        
def main():
    try:
        Sdm = SendMail()
        file_list = Sdm.getfiles()
        Sdm.readxls()
        if len(file_list)>0:
            for i in file_list:
                print i
                flg = Sdm.Sdmail(i)
                if flg:
                    os.remove(i)
                    print '%s has been deleted.' % i
            print 'All mails send done.'
        else:
            print 'No html files found in directory, Please check !'
    except Exception, e:
        traceback.print_exc()
        
    
if __name__ == '__main__':
    main()